var App = App||{};
App.init = function(){
	App.UserStats.init();
};

App.UserStats = {};

App.UserStats.init = function(){
	Highcharts.setOptions({
		credits: { enabled: false },
		colors: [ '#4572A7', '#AA4643', '#89A54E', '#80699B', '#3D96AE', '#DB843D', '#92A8CD', '#A47D7C', '#B5CA92', '#E0AB1A' ]
	});	
	
	var self = this;
	$('#userSelect').toChecklist({ submitDataAsArray: false, inputType: 'radio', cssChecked: '' });	// doesn't return the same
	$('#userSelect').delegate('.checklist :radio', 'change', function(){ self.Refresh.call(self, this.value); });
};


App.UserStats.Refresh = function(userId){
	$.ajax({ url: "hoursPerProject", context: this, data: {userId: userId, days:30} }).success(function(data){ this.pieChart('chart1', 'Hours per project - last 30 days', data); });	
	$.ajax({ url: "hoursPerProject", context: this, data: {userId: userId} }).success(function(data){ this.pieChart('chart2', 'Hours per project - all times', data); });	
};


App.UserStats.pieChart = function(containerId, title, data){
	// [{name:'', hours: ''},...]   == >  [['name',   45.0],...]
	var i = 0, row, newData = [];
	for (; row = data[i++] ;) newData.push([ row.name, row.hours ]);
	
	var conf = {
		chart: { renderTo: containerId, margin: [0, 0, 0, 100], backgroundColor: null },
		title: { text: title },
		plotOptions: { pie: { borderWidth: 1, borderColor: '#DDDDDD', shadow: false,
				dataLabels: { enabled: true, distance: -40, color: '#fff', formatter: function(){ 
					return '<b>'+ this.point.name +'</b><br/>'+ this.y +'h (' + Highcharts.numberFormat(this.percentage,0) +'%)';
				} } 
		}},
		tooltip: { enabled: false, formatter: function() { return '<b>'+ this.point.name +'</b><br/>'+ this.y +'h (' + Highcharts.numberFormat(this.percentage,0) +'%)'; } },
		legend: { enabled: true, layout: 'vertical', align: 'left', y: 30, verticalAlign: 'top', lineHeight: 20, borderWidth: 0 },
		series: [{ type: 'pie', name: title, data: newData, showInLegend: true }]
	};
	new Highcharts.Chart(conf);
};
